package team.bluepen.supermarket.util;

import team.bluepen.supermarket.data.entity.Product;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author RollW
 */
public class RandomProductGenerator {
    private static final Random RANDOM = new Random();
    private final List<String> names = new ArrayList<>();
    private int size;

    public RandomProductGenerator(File namesFile) throws IOException {
        this(Files.newInputStream(namesFile.toPath()));
    }

    public RandomProductGenerator(InputStream namesStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(namesStream));
        load(reader);
    }

    private void load(BufferedReader bufferedReader) throws IOException {
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            line = line.trim();
            if (line.startsWith("#") || line.isEmpty()) {
                continue;
            }
            names.add(line);
        }
        size = names.size();
        bufferedReader.close();
    }

    public Product next() {
        long userId = nextInt(0, 10000);
        long id = nextInt(10000, 12000);
        String name = nextName();
        int amount = nextInt(1, 280);
        int price = nextInt(1, 200);
        boolean state = !(RANDOM.nextBoolean() & (RANDOM.nextInt() & 2) == 0);

        return Product.builder()
                .setUserId(userId)
                .setName(name)
                .setId(id)
                .setAmount(amount)
                .setPrice(price)
                .setState(state)
                .build();
    }

    private String nextName() {
        int index = nextInt(0, size - 1);
        return names.get(index);
    }

    private int nextInt(int min, int max) {
        if (max - min < 0) {
            return RANDOM.nextInt(1) + min;
        }
        return RANDOM.nextInt(max - min) + min;
    }
}
